//
//  LatestNewsviewController.m
//  KG
//
//  Created by Eugene Braginets on 14.03.12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "LatestNewsviewController.h"
#import "AppDelegate.h"
#import "NewsItemViewController.h"
#import "WebService.h"
#import "NewsItem.h"
#import "JSONKit.h"
#import "bannerView.h"
#import "UIImage+Utilities.h"


@implementation LatestNewsviewController

@synthesize newsSummary = _newsSummary;
@synthesize contentView = _contentView;
@synthesize grayIndicator = _grayIndicator;
@synthesize newsImage=_newsImage;
@synthesize newsImage2=_newsImage2;
@synthesize SummaryTransparentBack = _SummaryTransparentBack;
@synthesize tableView=_tableView;
@synthesize newsItemToShow=_newsItemToShow;
@synthesize timer=_timer;
@synthesize pressed=_pressed;
@synthesize currentImageID=_currentImageID;
@synthesize errorMessage = _errorMessage;
@synthesize bannerViewController=_bannerViewController;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [[NSNotificationCenter defaultCenter] addObserver:self 
                                                 selector: @selector(loadData)
                                                     name:kNewsItem object: nil];	
        [[NSNotificationCenter defaultCenter] addObserver:self 
                                                 selector: @selector(updateUI)
                                                     name:@"updateui" 
                                                   object: nil];	
        self.newsItemToShow=0;
        self.pressed=NO;
        
    }
    return self;
}

#pragma mark - View lifecycle



- (void) viewWillAppear:(BOOL)animated {

   self.timer=[NSTimer scheduledTimerWithTimeInterval:10
                                                target:self
                                              selector:@selector(showNextNewsItem:)
                                              userInfo:nil
                                               repeats:YES];
    [self setTitle:@"Latest News"];
    [self loadData];
    
   
}


- (void)viewDidLoad
{
    
//    [self loadImage:[kNewsArray objectAtIndex:0]];
//    self.newsImage2.alpha=0;
//    
//    [self.newsImage setBackgroundColor:[UIColor clearColor]];
//    [self.newsImage2 setBackgroundColor:[UIColor clearColor]];
//    
    
    bannerView *bannerVC=[[bannerView alloc] init];
    [self.view addSubview:bannerVC.view];
    [bannerVC animate];
    self.bannerViewController=bannerVC;

    
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}


- (void)viewWillDisappear:(BOOL)animated {
    [self.timer invalidate];
    [super viewWillDisappear:animated];
}

- (void)viewDidUnload
{
   
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:kNewsItem
                                                  object:nil]; 
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:@"updateui"
                                                  object:nil]; 
    
    [self setNewsImage:nil];
    [self setNewsImage2:nil];
    [self setTableView:nil];
    [self setNewsSummary:nil];
    [self setSummaryTransparentBack:nil];
    [self setGrayIndicator:nil];
    [self setContentView:nil];
    [self setErrorMessage:nil];
    [super viewDidUnload];
    
    NSLog(@"ViewLatestNews unload");
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}



#pragma mark - custom methods

- (void) updateUI {
    NSLog(@"update UI");
    //    self.newsSummary.text=[[kNewsArray objectAtIndex:self.newsItemToShow]summary];
    //    [self.newsImage setImage:[[kNewsArray objectAtIndex:self.newsItemToShow] image]];
   
    [self showNews];
    [self.contentView setHidden:NO];
    [self.grayIndicator setHidden:YES];
    [self.tableView reloadData];
    
}

- (void) showNews {
    NSLog(@"Show News");
//    [self.newsImage setImage:item.image];
//    [self.newsImage setHidden:NO];
//    [self.newsImage setAlpha:1];
//    
    if ([kNewsArray count]==0) {
        return;
    }
    NewsItem *item=[kNewsArray objectAtIndex:self.newsItemToShow];
    

//    UIImage *img1=[UIImage imageNamed:@"default_news1high.png"];
    
    UIImage *img1=item.image;

    //    NSLog(@"IMage before %@   w:%f   h:%f    ratio:%f",item.name,img1.size.width, img1.size.height,img1.size.width/img1.size.height);
    
    float ratio=img1.size.width/img1.size.height;
    
    if (ratio<1.8) {
        //image is higher than field
        float heightShouldBe=img1.size.width/1.88;
        float cropHeight=(img1.size.height-heightShouldBe)/2;
        item.image=[img1 crop:CGRectMake(0, cropHeight, img1.size.width, heightShouldBe)];
        
    }
    
//    NSLog(@"IMage after %@   w:%f   h:%f    ratio:%f",item.name,img2.size.width, img2.size.height,img2.size.width/img2.size.height);

    [self.newsImage setContentMode:UIViewContentModeScaleAspectFill];
    [self.newsImage2 setContentMode:UIViewContentModeScaleAspectFill];
    
    [self.newsImage2 setImage:item.image];
    self.newsImage2.alpha = 0;
    [self.newsImage2 setHidden:NO];
    
    [UIView 
     animateWithDuration:0.4 
     delay:0.1 
     options:UIViewAnimationCurveEaseOut
     animations:^{
         self.newsSummary.text=item.summary;
         self.newsImage2.alpha=1;
         self.newsImage.alpha=0;
         if ([self.newsSummary.text length]<1) 
             [self.SummaryTransparentBack setHidden:YES];
         else
             [self.SummaryTransparentBack setHidden:NO];
     }
     completion:^(BOOL finished){
         [self.newsImage setImage:item.image];
         self.newsImage.alpha=1;
         self.newsImage2.alpha=0;
         [self.newsImage2 setHidden:YES];
       

     }
     ];
}
- (void) showNextNewsItem: (NSTimer*) theTimer {
    
    
    if ([kNewsArray count]==0) {
          return;
    }
    
    if (![self.newsImage image]) {
        NSLog(@"No image for %d %@",self.newsItemToShow, [[kNewsArray objectAtIndex:self.newsItemToShow] name]);
        NSOperationQueue *queue = [[NSOperationQueue alloc] init ];
        NSInvocationOperation *operation1 = [[NSInvocationOperation alloc] 
                                             initWithTarget:self
                                             selector:@selector(loadImage:) 
                                             object:[kNewsArray objectAtIndex:self.newsItemToShow]];
       [queue addOperation:operation1]; 
        return;
    }
    
    NSLog(@"NSTimer event #:%d",self.newsItemToShow);
     int len=[kNewsArray count]-2;
    

    
    if (self.newsItemToShow>len) {
        self.newsItemToShow=-1;
    }

    
    NSOperationQueue *queue = [NSOperationQueue new];
    
    if ((self.newsItemToShow+1)<len){
        NSInvocationOperation *operation = [[NSInvocationOperation alloc] 
                                            initWithTarget:self
                                            selector:@selector(loadImage:) 
                                            object:[kNewsArray objectAtIndex:self.newsItemToShow+1]];
    
    [queue addOperation:operation];
    }

        if ((self.newsItemToShow+2)<len){
            NSInvocationOperation *operation1 = [[NSInvocationOperation alloc] 
                                                initWithTarget:self
                                                selector:@selector(loadImage:) 
                                                object:[kNewsArray objectAtIndex:self.newsItemToShow+2]];
    [queue addOperation:operation1]; 
    }
       
     self.newsItemToShow=self.newsItemToShow+1;
  
    [[NSNotificationCenter defaultCenter]
     postNotificationName:@"updateui"
     object:nil];
    
//    [self performSelectorOnMainThread:@selector(showNews:) withObject:[kNewsArray objectAtIndex:self.newsItemToShow] waitUntilDone:NO];
    
    
  
    
}



- (void) loadData {
    
    NSLog (@"loadData");

    if ([kNewsArray count]==0) {
        [self.contentView setHidden:YES];
        return;
    }
//    NSOperationQueue *queue = [NSOperationQueue new];
//    NSInvocationOperation *operation = [[NSInvocationOperation alloc] 
//                                        initWithTarget:self
//                                        selector:@selector(loadImage:) 
//                                        object:[kNewsArray objectAtIndex:0]];
//    [queue addOperation:operation]; 
    
    
//    for (DataItem* item in kNewsArray){
//        NSOperationQueue *queue = [NSOperationQueue new];
//        NSInvocationOperation *operation = [[NSInvocationOperation alloc] 
//                                            initWithTarget:self
//                                            selector:@selector(loadImage:) 
//                                            object:item];
//        [queue addOperation:operation]; 
//    }
    
//    [self.newsSummary setShadowColor:[UIColor blackColor]];
//    [self.newsSummary setShadowOffset:CGSizeMake(1, 1)];
//    
    
    [[NSNotificationCenter defaultCenter]
     postNotificationName:@"updateui"
     object:nil];
    
//    [self performSelectorOnMainThread:@selector(showNews:) withObject:[kNewsArray objectAtIndex:self.newsItemToShow] waitUntilDone:NO];
//    [self performSelectorOnMainThread:@selector(updateUI) withObject:nil waitUntilDone:NO];

   
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [touches anyObject];
    
    if (([touch view] == self.newsImage2) || ([touch view] == self.newsImage))
    {
        int i;
        i=self.newsItemToShow;
        NSString *itemid=[NSString stringWithFormat:[[kNewsArray  objectAtIndex:i] itemid]];
        NSString *name=[NSString stringWithFormat:@"%@%@",kNewsItem, itemid];
            [self loadNewsItem:[kNewsArray objectAtIndex:i]];
        
        NewsItemViewController* newsItemViewController=[[NewsItemViewController alloc] initWithItemNews:name];
        
        [self setTitle:@"Back"];
        
            newsItemViewController.navigationItem.title=[[kNewsArray objectAtIndex:i] name];
            [self.navigationController pushViewController:newsItemViewController animated:YES];
        
    }
    
}



- (void) loadNewsItem: (NewsItem*) item {
    NSLog (@"load news item here");
    
    NSString *itemid=item.itemid;
    NSString *name=[NSString stringWithFormat:@"%@%@",kNewsItem,itemid];
    NSString *url=[NSString stringWithFormat:@"%@&item=%@",kGetNewsURL,itemid];
    
    [myAppDelegate getData:url andType:name];
    
}


- (void)loadImage:(NewsItem *)item {
    
    //    int ind=[index intValue];
    
    if (item.image) {
        NSLog (@"image is already loaded for itemId: %@",item.itemid);
        return;   
    }
    else {
        NSLog (@"loading image for itemId: %@",item.itemid);
    }
    
    NSString *imageAddr=[NSString stringWithString:item.imageAddr];
    
    NSLog (@"ImageUrl: %@", imageAddr);
    NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imageAddr]];
    UIImage* image = [[UIImage alloc] initWithData:imageData];
    [item setImage:image];
    
    [[NSNotificationCenter defaultCenter]
     postNotificationName:@"updateui"
     object:item];

    
//    [self performSelectorOnMainThread:@selector(imageDidLoad:) withObject:item waitUntilDone:NO];
}

- (void) imageDidLoad:(NewsItem *)item {
    NSLog (@"image for itemId:%@ is loaded!",item.itemid);
    [[NSNotificationCenter defaultCenter]
     postNotificationName:@"updateui"
     object:nil];
    
//    [self performSelectorOnMainThread:@selector(showNews:) withObject:[kNewsArray objectAtIndex:self.newsItemToShow] waitUntilDone:NO];
  }



#pragma mark - TableView  delegate

// Customize the number of sections in the table view.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 70;    
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [kNewsArray  count];
}



// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *MyIdentifier = @"MyIdentifier";
    MyIdentifier = @"tblCellView";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:MyIdentifier];
    }
    
	cell.textLabel.text=[[kNewsArray  objectAtIndex:indexPath.row] name];
    [cell.textLabel setLineBreakMode:UILineBreakModeWordWrap];
    [cell.textLabel setNumberOfLines:2];
   
    cell.detailTextLabel.text=[[kNewsArray  objectAtIndex:indexPath.row] publishdate];
    

    
    [cell.detailTextLabel setTextColor:[UIColor whiteColor]];
//   
//    [cell.imageView setImage:[[kNewsArray  objectAtIndex:indexPath.row] image]];
    UIView *bgColorView = [[UIView alloc] init];
    [bgColorView setBackgroundColor:[UIColor colorWithRed:.25 green:.3 blue:.05 alpha:0.7]];
    
    [cell setSelectedBackgroundView:bgColorView];
    
    //[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
    
    [cell setAccessoryView:[self makeDetailDisclosureButton]];

    return cell;
}


- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    [cell setBackgroundColor:[UIColor clearColor]];   
    if (indexPath.row!=self.newsItemToShow){
        UIView *bgColorView = [[UIView alloc] init];
        [bgColorView setBackgroundColor:[UIColor clearColor]];
        [cell setBackgroundView:bgColorView];        
    }
    else {
        UIView *bgColorView = [[UIView alloc] init];
        [bgColorView setBackgroundColor:[UIColor colorWithRed:.25 green:.3 blue:.05 alpha:0.7]];
        [cell setBackgroundView:bgColorView];        
        [tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog (@"selected row %d", indexPath.row);

    [self performSelectorOnMainThread:@selector(showNews) withObject:nil waitUntilDone:NO];
    self.newsItemToShow=indexPath.row;
    NSString* itemid=[[kNewsArray objectAtIndex:indexPath.row] itemid];
    NSString*  name=[NSString stringWithFormat:@"%@%@",kNewsItem,itemid];
    
    //check if array with news exists
    if ([kNewsArray  count]>indexPath.row) {
           
        [self loadNewsItem:[kNewsArray objectAtIndex:indexPath.row]];
        }
        
    NewsItemViewController* newsItemViewController=[[NewsItemViewController alloc] initWithItemNews:name];
    
    [[NSNotificationCenter defaultCenter]
     postNotificationName:@"updateui"
     object:nil];
    
//    [self showNews:[kNewsArray objectAtIndex:indexPath.row]];
    [self setTitle:@"Back"];
   
    [myAppDelegate loadImage:[kNewsArray objectAtIndex:indexPath.row]];
    
    [self.navigationController pushViewController:newsItemViewController animated:YES];
    
    
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
    NSLog (@"selected accessory from row %d", indexPath.row);

    NSString* itemid=[[kNewsArray objectAtIndex:indexPath.row] itemid];
     NSString*  name=[NSString stringWithFormat:@"%@%@",kNewsItem,itemid];
    [self loadNewsItem:[kNewsArray objectAtIndex:indexPath.row]];
    
   NewsItemViewController* newsItemViewController=[[NewsItemViewController alloc] initWithItemNews:name];

    [self setTitle:@"Back"];
    
    if (newsItemViewController) {
        newsItemViewController.navigationItem.title=[[kNewsArray objectAtIndex:indexPath.row] name];
        [self.navigationController pushViewController:newsItemViewController animated:YES];
    }
}

//helper for accessoryButtonTapped
- (void) accessoryButtonTapped: (UIControl *) button withEvent: (UIEvent *) event
{
    NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint: [[[event touchesForView: button] anyObject] locationInView: self.tableView]];
    if ( indexPath == nil )
        return;
    [self.tableView.delegate tableView: self.tableView accessoryButtonTappedForRowWithIndexPath: indexPath];
}

- (UIButton *) makeDetailDisclosureButton {
    UIButton * button =[UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:@"rightarrow"] forState:UIControlStateNormal];
    [button setBackgroundColor:[UIColor clearColor]];
    [button setFrame:CGRectMake(0, 0, 25, 25)];
    
    [button setImage:[UIImage imageNamed:@"rightarrow"] forState:UIControlStateHighlighted];
    [button setImage:[UIImage imageNamed:@"rightarrow_pressed"] forState:UIControlStateSelected];
    [button setImage:[UIImage imageNamed:@"rightarrow_pressed"] forState:UIControlStateHighlighted];
    
    [button addTarget: self
               action: @selector(accessoryButtonTapped:withEvent:)
     forControlEvents: UIControlEventTouchUpInside];
    
    return ( button );
}

#pragma mark - other methods
- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    
    NSLog(@"Memory warning from Latest News");
    [super didReceiveMemoryWarning];
    
    
    // Release any cached data, images, etc that aren't in use.
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
